'Copyright (C) 2009 Christiaan Cable
'
'This program is free software; you can redistribute it and/or
'modify it under the terms of the GNU General Public License
'as published by the Free Software Foundation; either version 3
'of the License, or (at your option) any later version.
'
'This program is distributed in the hope that it will be useful,
'but WITHOUT ANY WARRANTY; without even the implied warranty of
'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'GNU General Public License for more details (LICENCE.TXT).

Imports System.Windows.Forms


Public Class Optus
    Public ISPReturnData As New ISPReturnData
    Private CookieContainer As New System.Net.CookieContainer

    Public Sub New(ByVal ConfigurationData As ConfigurationData)

        Try
            'set rollover date
            SetRolloverDate(ConfigurationData, ISPReturnData)

            Dim strHTMLData As String

            'login 
            Dim userNameWithoutDomainName As String = ConfigurationData.Username.ToLower.Replace("@optusnet.com.au", "")

            Dim POSTData As String = "spEntityID=https://optussmartsafe.optus.com.au/shibboleth&j_username=" & userNameWithoutDomainName & "&j_password=" & ConfigurationData.Password & "&j_principal_type=ISP&j_security_check=true&rememberMe=on"
            strHTMLData = ISPPost("https://idp.optusnet.com.au/idp/optus/Authn/Service/ISP", POSTData, CookieContainer, System.Net.CredentialCache.DefaultCredentials)

            'If UA.DebugISP = True Then
            '    My.Computer.FileSystem.WriteAllText(GetAppDataPath() & "debug_loginresult.htm", strHTMLData, False, System.Text.Encoding.ASCII)
            '    For Each cookie As System.Net.Cookie In CookieContainer.GetCookies(New Uri("https://idp.optusnet.com.au/idp/optus/Authn/Service/ISP"))
            '        My.Computer.FileSystem.WriteAllText(GetAppDataPath() & "debug_cookies.txt", String.Format("Date/Time: {0} Name: {1}, Value: {2}, Path: {3}", DateTime.Now.ToString(), cookie.Name, cookie.Value, cookie.Path) & vbCrLf, True, System.Text.Encoding.ASCII)
            '    Next
            'End If


            If strHTMLData.Contains("Invalid username or password") = True And Not Debugger.IsAttached Then
                ISPReturnData.ErrorMessage = "Login Failed"
                Exit Sub
            End If

            'usage
            strHTMLData = ISPGet("https://memberservices.optuszoo.com.au/myusage/", CookieContainer, System.Net.CredentialCache.DefaultCredentials)

            If Debugger.IsAttached Then
                '--------------------
                'Debugging only
                Dim reader As System.IO.StreamReader = New System.IO.StreamReader("D:\temp\OptusOldPlan.txt")
                strHTMLData = reader.ReadToEnd()
                reader.Close()
                '---------------------
            End If

            If UA.DebugISP = True Then
                My.Computer.FileSystem.WriteAllText(GetAppDataPath() & "debug_usage.htm", strHTMLData, False, System.Text.Encoding.ASCII)
                'For Each cookie As System.Net.Cookie In CookieContainer.GetCookies(New Uri("https://idp.optusnet.com.au/idp/optus/Authn/Service/ISP"))
                '    My.Computer.FileSystem.WriteAllText(GetAppDataPath() & "debug_cookies.txt", String.Format("Date/Time: {0} Name: {1}, Value: {2}, Path: {3}", DateTime.Now.ToString(), cookie.Name, cookie.Value, cookie.Path) & vbCrLf, True, System.Text.Encoding.ASCII)
                'Next
            End If


            'logout
            'ISPGet("https://memberservices.optuszoo.com.au/?logout=1", CookieContainer, System.Net.CredentialCache.DefaultCredentials)

            '##################################################################################

            'strHTMLData = My.Computer.FileSystem.ReadAllText("C:\programming\isp\optus\myusage4.htm", System.Text.Encoding.ASCII)

            'process response
            Dim PlanType As String = ExtractText(strHTMLData, "Current Plan:", 0, "<i>", "<")
            Dim LastUpdated As String

            If PlanType <> "" Then
                If PlanType.Contains("Fusion") Then
                    ISPReturnData.PeakUpload = CSng(Val(ExtractText(strHTMLData, "<td headers='planDataU'", 0, ">", "<")))
                    ISPReturnData.PeakDownload = CSng(Val(ExtractText(strHTMLData, "<td headers='planDataU'", 20, ">", "<")))
                    LastUpdated = ExtractText(strHTMLData, "Last Update:", 0, "<td >", "  ")
                    ISPReturnData.LastUpdated = Date.ParseExact(LastUpdated, "dd MMM yy hh:mmtt", Nothing)

                ElseIf PlanType.Contains("GB monthly data usage") = True Or PlanType.Contains("'yes'") And PlanType <> "'yes' Power" Then
                    ISPReturnData.PeakUpload = CSng(Val(ExtractText(strHTMLData, "<td headers='planDataU'", 0, ">", "<")))
                    ISPReturnData.PeakDownload = CSng(Val(ExtractText(strHTMLData, "<td headers='planDataU'", 20, ">", "<")))
                    LastUpdated = Trim(ExtractText(strHTMLData, "Last Update:", 0, "<td >", " AET"))
                    ISPReturnData.LastUpdated = Date.ParseExact(LastUpdated, "dd MMM yy hh:mmtt", Nothing)

                Else
                    'fallback to old plan type
                    ISPReturnData.PeakDownload = CSng(Val(ExtractText(strHTMLData, "<td headers='planDataU'", 0, ">", "<", 3)))
                    ISPReturnData.OffpeakDownload = CSng(Val(ExtractText(strHTMLData, "<td headers='yesDataU'", 0, ">", "<")))
                    LastUpdated = ExtractText(strHTMLData, "Last Update:", 0, "<td >", "  ")
                    ISPReturnData.LastUpdated = Date.ParseExact(LastUpdated, "dd MMM yy hh:mmtt", Nothing)
                End If

            Else
                'try alternate layout
                PlanType = ExtractText(strHTMLData, "Current Plan:", 0, "plan"">", "<")

                If PlanType.Contains("Fusion") = True Then
                    ISPReturnData.PeakUpload = CSng(Val(ExtractText(strHTMLData, "<th>Upload</th>", 0, "<td>", "<")))
                    ISPReturnData.PeakDownload = CSng(Val(ExtractText(strHTMLData, "<td>" & ExtractText(strHTMLData, "<th>Upload</th>", 0, "<td>", "<") & "</td>", 0, "<td>", "<")))

                    'ISPReturnData.LastUpdated = CDate(ExtractText(strHTMLData, "Last Update:", 0, "update"">", " AET"))
                    LastUpdated = ExtractText(strHTMLData, "Last Update:", 0, "update"">", " AET")
                    ISPReturnData.LastUpdated = Date.ParseExact(LastUpdated, "dd MMM yy hh:mmtt", Nothing)

                Else
                    ISPReturnData.ErrorMessage = "Error parsing website"
                    Exit Sub
                End If
            End If

            '##########################################################

            ProcessISPData(ConfigurationData, ISPReturnData)

            'check for error
            If ISPReturnData.ErrorMessage <> "" Then Exit Sub

            '##########################################################

            'create graph data
            If PlanType.Contains("Fusion") = True Or PlanType.Contains("GB monthly data usage") = True Or PlanType.Contains("'yes'") And PlanType <> "'yes' Power" = True Then
                ISPReturnData.GraphItemList.Add(New GraphItem("Usage " & Format(System.Math.Floor(((ISPReturnData.PeakDownload + ISPReturnData.PeakUpload) / Val(ConfigurationData.PeakUsageLimit)) * 1000) / 10, "#0.0") & "% (" & ISPReturnData.PeakDownload + ISPReturnData.PeakUpload & " MB)", ISPReturnData.PeakDownload + ISPReturnData.PeakUpload, CSng(Val(ConfigurationData.PeakUsageLimit)), False))
            Else
                If ConfigurationData.OffpeakAvailable = True Then
                    'peak
                    ISPReturnData.GraphItemList.Add(New GraphItem("Peak " & Format(System.Math.Floor((ISPReturnData.PeakDownload / Val(ConfigurationData.PeakUsageLimit)) * 1000) / 10, "#0.0") & "% (" & ISPReturnData.PeakDownload & " MB)", ISPReturnData.PeakDownload, CSng(Val(ConfigurationData.PeakUsageLimit)), ISPReturnData.PeakNow))

                    'offpeak
                    ISPReturnData.GraphItemList.Add(New GraphItem("Offpeak " & Format(System.Math.Floor((ISPReturnData.OffpeakDownload / Val(ConfigurationData.OffpeakUsageLimit)) * 1000) / 10, "#0.0") & "% (" & ISPReturnData.OffpeakDownload & " MB)", ISPReturnData.OffpeakDownload, CSng(Val(ConfigurationData.OffpeakUsageLimit)), ISPReturnData.OffpeakNow))
                Else
                    ISPReturnData.GraphItemList.Add(New GraphItem("Peak " & Format(System.Math.Floor((ISPReturnData.PeakDownload / Val(ConfigurationData.PeakUsageLimit)) * 1000) / 10, "#0.0") & "% (" & ISPReturnData.PeakDownload & " MB)", ISPReturnData.PeakDownload, CSng(Val(ConfigurationData.PeakUsageLimit)), False))
                End If
            End If

            'days elapsed
            ISPReturnData.GraphItemList.Add(New GraphItem("Days Elapsed " & Format((ISPReturnData.DaysUsed / (ISPReturnData.DaysUsed + ISPReturnData.DaysLeft)) * 100, "#0") & "% (" & ISPReturnData.DaysUsed & " Days)", ISPReturnData.DaysUsed, ISPReturnData.DaysUsed + ISPReturnData.DaysLeft, False))

            '##########################################################

            'create stats data
            If PlanType.Contains("Fusion") = True Or PlanType.Contains("GB monthly data usage") = True Or PlanType.Contains("'yes'") = True And PlanType <> "'yes' Power" Then
                ISPReturnData.TextItemList.Add(New TextItem("Usage Left :", ISPReturnData.PeakUsageRemainingDescription))
                ISPReturnData.TextItemList.Add(New TextItem("Usage Avg. Left :", ISPReturnData.PeakUsageRemainingPerDayDescription))

                ISPReturnData.TextItemList.Add(New TextItem("Downloads :", ISPReturnData.PeakDownload & " MB"))
                ISPReturnData.TextItemList.Add(New TextItem("Uploads :", ISPReturnData.PeakUpload & " MB"))
            Else
                ISPReturnData.TextItemList.Add(New TextItem("Peak Left :", ISPReturnData.PeakUsageRemainingDescription))
                ISPReturnData.TextItemList.Add(New TextItem("Peak Avg. Left :", ISPReturnData.PeakUsageRemainingPerDayDescription))

                If ConfigurationData.OffpeakAvailable = True Then
                    ISPReturnData.TextItemList.Add(New TextItem("Offpeak Left :", ISPReturnData.OffpeakUsageRemainingDescription))
                    ISPReturnData.TextItemList.Add(New TextItem("Offpeak Avg. Left :", ISPReturnData.OffpeakUsageRemainingPerDayDescription))
                End If
            End If

            If ISPReturnData.ShapedNow = False Then
                ISPReturnData.TextItemList.Add(New TextItem("Shaped :", "NO"))
            Else
                ISPReturnData.TextItemList.Add(New TextItem("Shaped :", "YES"))
            End If

            '##########################################################

            'process alerts
            ProcessAlerts(ConfigurationData, ISPReturnData)

        Catch ex As Exception
            ISPReturnData.ErrorMessage = ex.Message
        End Try

    End Sub

End Class
